package comRedis

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"time"
)

type RedisConfig struct {
	Host     string
	Pass     string
	DbNumber int
}

func GetRdb(c *RedisConfig) *redis.Client {
	rdb := redis.NewClient(&redis.Options{
		Addr: c.Host, // Redis 服务器地址
		//Password: c.Pass,     // 如果 Redis 服务器设置了密码，则在此填写
		DB: c.DbNumber, // 使用默认数据库
	})
	return rdb
}

type RedisPrams struct {
	Ctx            context.Context
	Rdb            *redis.Client
	Key            string
	Expiration     time.Duration
	LockKey        string
	LockValue      string
	LockExpiration time.Duration
}

// 获取锁
func (l *RedisPrams) acquireLock() (bool, error) {
	success, err := l.Rdb.SetNX(l.Ctx, l.LockKey, l.LockValue, l.LockExpiration).Result()
	return success, err
}

// 释放锁
func (l *RedisPrams) releaseLock() (bool, error) {
	luaScript := `
	   if redis.call("get", KEYS[1]) == ARGV[1] then
	       return redis.call("del", KEYS[1])
	   else
	       return 0
	   end
	`
	result, err := l.Rdb.Eval(l.Ctx, luaScript, []string{l.LockKey}, l.LockValue).Result()
	fmt.Println("释放锁：", l.LockKey, l.LockValue)
	return result == int64(1), err
}
